package algorithm;

/**
 * 搜索算法
 *
 * @author luoyalan
 * @date 2018/7/29
 */
public class Search {

    /**
     * 二分查找
     *
     * @param sorted     有序数组
     * @param data       需要查找的序列
     * @param startIndex 起始索引
     * @param endIndex   结束索引
     * @return 返回位置
     */
    public static int binarySearch(int[] sorted, int data, int startIndex, int endIndex) {
        if (sorted == null || sorted.length < 1) {
            return -1;
        }
        if (startIndex > endIndex) {
            return -1;
        }

        int index = (startIndex + endIndex) / 2;
        if (sorted[index] == data) {
            return index;
        }
        if (sorted[index] > data) {
            return binarySearch(sorted, data, startIndex, index);
        }
        if (sorted[index] < data) {
            return binarySearch(sorted, data, index, endIndex);
        }
        return 0;
    }

    public static void main(String[] args) {
        int[] sort = {1, 2, 3, 4,5};
        System.out.println(binarySearch(sort, 3, 0, 3));
    }
}
